import React, { useState, useEffect } from 'react';
import { Row, Col } from 'antd';
import LineStackChart from 'src/components/Chart/LineStackChart';
import PieDoughnutChart from 'src/components/Chart/PieDoughnut';
import FilterTool from 'src/components/FilterTool';
import '../../../StrategyLabs/Detail/index.less';
import services from 'src/services/api';
import { round, bitTrans } from 'src/utils/utils';
import { tooltipFormatter } from '../utils';
import moment from 'moment';

export default function ServicesMonitor() {
  const [list, setList] = useState([]);
  const [cpu, setCpu] = useState([]); // CPU使用率
  const [memory, setMemory] = useState([]); // 内存使用率
  const [load, setLoad] = useState([]); // 服务器负载
  const [disk, setDisk] = useState([]); // 磁盘IO使用率
  const [network, setNetwork] = useState([]); //
  const [storage, setStorage] = useState([]); //

  useEffect(() => {
    getServicesList();
  }, []);

  function getStatistics(params, type = true) {
    if (!type) return;
    serverMonitor({ ...params, type: 'cpu' });
    serverMonitor({ ...params, type: 'memory' });
    serverMonitor({ ...params, type: 'load' });
    serverMonitor({ ...params, type: 'network' });
    serverMonitor({ ...params, type: 'disk' });
    serverMonitor({ ...params, type: 'storage' });
  }

  function getServicesList() {
    services.devOpt.serverList({}).then((res) => {
      if (res.code === 0) {
        setList(res.data);
      }
    });
  }

  function serverMonitor(params) {
    services.devOpt.serverMonitor(params).then((res) => {
      if (res.code === 0) {
        switch (params.type) {
          case 'cpu':
            setCpu(res.data);
            break;
          case 'memory':
            setMemory(res.data);
            break;
          case 'load':
            setLoad(res.data);
            break;
          case 'network':
            setNetwork(res.data);
            break;
          case 'disk':
            setDisk(res.data);
            break;
          case 'storage':
            setStorage(res.data);
            break;
          default:
            break;
        }
      }
    });
  }

  const filterItems = [
    {
      type: 'Select',
      key: 'server_ip',
      name: 'server_ip',
      label: '服务器',
      defaultValue: list[0] && list[0].ip,
      allowClear: true,
      options: list.map((it) => {
        return { name: it.name, value: it.ip };
      }),
    },
    {
      type: 'rangepicker',
      key: 'start',
      name: ['start', 'end'],
      label: '统计时间',
      defaultValue: [
        moment()
          .subtract(6, 'day')
          .startOf('day')
          .format('YYYY-MM-DD HH:mm'),
        moment().format('YYYY-MM-DD HH:mm'),
      ],
      disabledDate: (current) => {
        return (
          current &&
          (current > moment().endOf('day') ||
            current <
              moment()
                .subtract(30, 'day')
                .endOf('day'))
        );
      },
      ranges: {
        本周: [moment().startOf('week'), moment()],
        近7天: [moment().subtract('days', 6), moment()],
        本月: [moment().startOf('month'), moment()],
        近30天: [moment().subtract('days', 29), moment()],
      },
      format: 'YYYY-MM-DD HH:mm',
      placeholder: ['起始时间', '结束时间'],
      allowClear: false,
    },
  ];
  const storageTotal = storage.reduce((total, it) => {
    total += Number(it.value);
    return total;
  }, 0);

  const [unit, bitNum] = bitTrans(storageTotal, 'B');
  const storageTotalX = storage.reduce((total, it) => {
    total += round(Number(it.value) / bitNum, 2) * 100;
    return total;
  }, 0);

  const [maxNetWork, minNetWork] = network.reduce(
    ([max, min], item) => {
      const [itemMax, itemMin] = item.value.reduce(
        ([itMax, itMin], it) => {
          itMax = itMax > Number(it[1]) ? itMax : Number(it[1]);
          itMin = itMin < Number(it[1]) ? itMin : Number(it[1]);
          return [itMax, itMin];
        },
        [0, 0]
      );
      return [max > itemMax ? max : itemMax, min < itemMin ? min : itemMin];
    },
    [0, 0]
  );
  const [unitNetwork, bitNumNetwork] =
    maxNetWork / minNetWork < 1024 ? bitTrans(maxNetWork, 'bps') : bitTrans(maxNetWork / 1024, 'bps');

  return (
    <div className='detail-page'>
      {list.length > 0 && (
        <FilterTool
          data={filterItems}
          colNum={4}
          query={getStatistics}
          refreshFilter={getStatistics}
          isOnChange={true}
          justify='start'
        />
      )}

      <Row gutter={20} style={{ marginTop: '20px' }}>
        <Col span={12} style={{ marginBottom: '20px' }}>
          <div className='risk-trend-box'>
            <div className='chart-head'>
              <h4>CPU使用率</h4>
            </div>
            <div className='chart-box'>
              <LineStackChart
                id='cpu'
                width='100%'
                height='300px'
                dataSource={cpu}
                xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                dataKey={1}
                dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                dataFormatter={'{value} %'}
                tooltipFormatter={(params) => {
                  return tooltipFormatter(params, 2, [1, '%']);
                }}
              />
            </div>
          </div>
        </Col>
        <Col span={12} style={{ marginBottom: '20px' }}>
          <div className='risk-trend-box'>
            <div className='chart-head'>
              <h4>内存使用率</h4>
            </div>
            <div className='chart-box'>
              <LineStackChart
                id='memory'
                width='100%'
                height='300px'
                dataSource={memory}
                xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                dataKey={1}
                dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                dataFormatter={`{value} %`}
                tooltipFormatter={(params) => {
                  return tooltipFormatter(params, 2, [1, '%']);
                }}
              />
            </div>
          </div>
        </Col>
        <Col span={12} style={{ marginBottom: '20px' }}>
          <div className='risk-trend-box'>
            <div className='chart-head'>
              <h4>平均负载</h4>
            </div>
            <div className='chart-box'>
              <LineStackChart
                id='load'
                width='100%'
                height='300px'
                dataSource={load}
                xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                dataKey={1}
                dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                tooltipFormatter={(params) => {
                  return tooltipFormatter(params, 2);
                }}
              />
            </div>
          </div>
        </Col>
        <Col span={12} style={{ marginBottom: '20px' }}>
          <div className='risk-trend-box'>
            <div className='chart-head'>
              <h4>网络流量</h4>
            </div>
            <div className='chart-box'>
              <LineStackChart
                id='network'
                width='100%'
                height='300px'
                dataSource={network}
                xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                dataKey={1}
                dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                dataFormatter={(params) => {
                  const flostNum = unitNetwork === 'Kbps' ? 0 : 2;
                  return round(params / bitNumNetwork, flostNum) + unitNetwork;
                }}
                tooltipFormatter={(params) => {
                  return tooltipFormatter(params, 2, [bitNumNetwork, unitNetwork]);
                }}
              />
            </div>
          </div>
        </Col>
        <Col span={12} style={{ marginBottom: '20px' }}>
          <div className='risk-trend-box'>
            <div className='chart-head'>
              <h4>存储状态</h4>
            </div>
            <div className='chart-box'>
              <PieDoughnutChart
                id='storage'
                width='100%'
                height='300px'
                dataSource={storage}
                legend={storage.length > 0 ? storage.map((it) => it.name) : []}
                total={{
                  title: '储存空间',
                  value: round(storageTotalX / 100) + unit,
                }}
                dataFormatter={(params) => {
                  return params.name + ':\n' + params.percent + '%(' + round(params.value / bitNum, 2) + unit + ')';
                }}
                tooltipFormatter={(params) => {
                  return (
                    params.marker +
                    params.name +
                    ':' +
                    params.percent +
                    '%<br/>' +
                    round(params.value / bitNum, 2) +
                    unit
                  );
                }}
              />
            </div>
          </div>
        </Col>
        <Col span={12} style={{ marginBottom: '20px' }}>
          <div className='risk-trend-box'>
            <div className='chart-head'>
              <h4>磁盘IO使用率</h4>
            </div>
            <div className='chart-box'>
              <LineStackChart
                id='disk'
                width='100%'
                height='300px'
                dataSource={disk}
                xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                dataKey={1}
                dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                dataFormatter={`{value} %`}
                tooltipFormatter={(params) => {
                  return tooltipFormatter(params, 4, [1, '%']);
                }}
              />
            </div>
          </div>
        </Col>
      </Row>
    </div>
  );
}
